package com.dongdongshop.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.dongdongshop.mapper.TbContentMapper;
import com.dongdongshop.page.PageResult;
import com.dongdongshop.pojo.*;
import com.dongdongshop.service.TbContentService;
import com.dongdongshop.utils.ContentUilt;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Arrays;
import java.util.List;

@Service
@DubboService
public class TbContentServiceImpl implements TbContentService {

    @Autowired
    private TbContentMapper contentMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public TbContent selectContentById(Long id) {
        return contentMapper.selectByPrimaryKey(id);
    }

    @Override
    public void updateContent(TbContent content) {
        contentMapper.updateByPrimaryKeySelective(content);
    }

    @Override
    public List<TbContent>  selectContentByCateId(Long id) {
        //判断缓存中是否有key
        if(redisTemplate.hasKey(ContentUilt.CONTENTREDIS + id)){
            String s = redisTemplate.opsForValue().get(ContentUilt.CONTENTREDIS + id);
            List<TbContent> contentList = JSONUtil.toList(s, TbContent.class);
            return contentList;
        }else {
            List<TbContent> contentList = contentMapper.selectByCateId(id);
            String s = JSON.toJSONString(contentList);
            redisTemplate.opsForValue().set(ContentUilt.CONTENTREDIS + id,s);
            return contentList;
        }
    }

    @Override
    public void deleteConts(Long[] ids) {
        TbContentExample example = new TbContentExample();
        TbContentExample.Criteria criteria = example.createCriteria();
        criteria.andIdIn(Arrays.asList(ids));
        contentMapper.deleteByExample(example);
    }

    @Override
    public void addContent(TbContent content) {
        contentMapper.insertSelective(content);
    }

    @Override
    public PageResult<TbContent> listContent(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<TbContent> list =  contentMapper.selectByExample(null);
        PageInfo<TbContent> i = new PageInfo<>(list);
        return new PageResult<>(i.getPageNum(),i.getPageSize(),i.getTotal(),i.getPages(),i.getList());
    }
}
